package org.example.loginAop.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.example.loginAop.annotation.AnnAop;
import org.example.loginAop.utils.JwtUtils;
import org.example.loginAop.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Aspect
@Component
public class LoginAop {
    @Pointcut("@annotation(org.example.loginAop.annotation.AnnAop)")
    public void pointCut(){

    }
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Around("pointCut()&&@annotation(annAop)")
    public Object  checkPermissopm(ProceedingJoinPoint joinPoint, AnnAop annAop) throws Throwable {
        String ip = request.getRemoteAddr();
        String token = (String) redisTemplate.opsForValue().get("token"+ip);
        Map map = (Map) JwtUtils.parseToken(token);
        Integer id = (Integer) map.get("id");
        String roleCoding = (String) map.get("roleCoding");
        String value = annAop.value();
        if(!value.equals(roleCoding)){
            return Result.fail("权限不足");
        }
        return joinPoint.proceed();
    }
}
